<template>
  <div class="chat-app">
    <!-- 顶部导航栏 -->
    <header class="app-header">
      <div class="header-content">
        <div class="logo-section">
          <el-icon class="logo-icon"><ChatLineSquare /></el-icon>
          <h1 class="app-title">智能聊天系统</h1>
        </div>
        <div class="user-actions">
          <div class="user-profile">
            <el-avatar size="small" :icon="UserFilled" :title="currentUser?.username"></el-avatar>
            <span class="username">{{ currentUser?.username || '加载中...' }}</span>
            <el-badge v-if="isAdmin" value="管理员" type="danger" size="small" class="admin-badge" />
          </div>
          <el-button type="primary" size="small" @click="showCreateRoomDialog = true" class="create-room-btn">
            <el-icon><Plus /></el-icon>
            创建聊天室
          </el-button>
          <el-button type="text" @click="handleLogout" class="logout-btn">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-layout">
      <!-- 左侧聊天室列表 -->
      <aside class="sidebar">
        <div class="sidebar-header">
          <h2>聊天室</h2>
        </div>
        <div class="room-list">
          <!-- AI聊天室 -->
          <div 
            class="room-item" 
            :class="{ active: currentRoom?.id === aiRoom?.id }"
            :key="aiRoom?.id"
            @click="switchRoom(aiRoom)"
          >
            <div class="room-icon">
              <el-icon class="ai-icon"><ChatDotRound /></el-icon>
            </div>
            <div class="room-info">
              <div class="room-name">AI 助手</div>
              <div v-if="currentRoom?.id === aiRoom?.id" class="room-status">
                <span class="model-indicator">{{ currentModel.name }}</span>
              </div>
            </div>
          </div>
          
          <!-- 用户聊天室列表 -->
          <div 
            v-for="room in chatRooms" 
            :key="room.id"
            class="room-item"
            :class="{ active: currentRoom?.id === room.id }"
          >
            <div class="room-content" @click="switchRoom(room)">
              <div class="room-icon">
                <el-icon v-if="room.roomType === 'private'" class="private-icon">
                  <User />
                </el-icon>
                <el-icon v-else class="group-icon">
                  <ChatLineSquare />
                </el-icon>
              </div>
              <div class="room-info">
                <div class="room-name">{{ room.name }}</div>
                <div class="room-type">{{ room.roomType === 'private' ? '私聊' : '群聊' }}</div>
              </div>
            </div>
            <el-button 
              v-if="isAdmin" 
              type="danger" 
              size="small" 
              icon="Delete" 
              @click.stop="deleteRoom(room.id)"
              class="delete-room-btn"
              title="删除聊天室"
            ></el-button>
          </div>
        </div>
      </aside>

      <!-- 右侧聊天区域 -->
      <section class="chat-container" v-if="currentRoom">
        <!-- 聊天室标题栏 -->
        <div class="chat-header">
          <div class="room-title-section">
            <h2 class="room-title">{{ currentRoom.name }}</h2>
            <span class="room-type-badge" :class="`badge-${currentRoom.roomType}`">
              {{ currentRoom.roomType === 'private' ? '私聊' : currentRoom.roomType === 'group' ? '群聊' : 'AI 聊天' }}
            </span>
          </div>
          
          <!-- AI模型选择器 -->
          <div v-if="currentRoom.roomType === 'ai'" class="model-selector">
            <el-dropdown @command="onModelChange" trigger="click">
              <span class="model-selector-trigger">
                <el-icon><Setting /></el-icon>
                <span>当前模型：{{ currentModel.name }}</span>
                <el-icon class="arrow-icon"><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item disabled>免费模型</el-dropdown-item>
                  <el-dropdown-item 
                    v-for="model in getModelsByType('free')" 
                    :key="model.id"
                    :command="model"
                    :disabled="selectedModelId === model.id"
                  >
                    <div class="dropdown-model-item">
                      <span class="dropdown-model-name">{{ model.name }}</span>
                      <span class="dropdown-model-desc">{{ model.description }}</span>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item divided disabled>高级模型</el-dropdown-item>
                  <el-dropdown-item 
                    v-for="model in getModelsByType('premium')" 
                    :key="model.id"
                    :command="model"
                    :disabled="selectedModelId === model.id"
                  >
                    <div class="dropdown-model-item">
                      <span class="dropdown-model-name">{{ model.name }}</span>
                      <span class="dropdown-model-desc">{{ model.description }}</span>
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <!-- 聊天消息区域 -->
        <div class="message-list" ref="messageList">
          <transition-group name="message-fade" tag="div">
            <div 
              v-for="message in messages" 
              :key="message.id" 
              :class="['message-wrapper', message.senderType === 'user' ? 'user-message-wrapper' : 'ai-message-wrapper']"
            >
              <div class="message-bubble" 
                   @click="message.fileMetadata && handleFileClick(message)"
                   :class="{ 'file-message': message.fileMetadata }">
                <div class="message-header">
                  <span class="message-sender">
                    {{ message.senderType === 'user' ? (message.senderName || currentUser?.username) : 
                      (currentRoom?.roomType === 'ai' ? 'AI 助手' : '系统消息') }}
                  </span>
                  <span class="message-time">{{ formatDate(message.timestamp) }}</span>
                </div>
                <div class="message-content" v-html="formatMessageContent(message)">
                </div>
                <div v-if="message.error" class="message-error">
                  {{ message.error }}
                </div>
              </div>
            </div>
          </transition-group>
          
          <!-- 空消息提示 -->
          <div v-if="messages.length === 0" class="empty-state">
            <el-empty 
              :image-size="100" 
              description="开始对话吧！"
              v-if="currentRoom?.roomType === 'ai'"
            >
              <template #description>
                <p>与AI助手进行智能对话</p>
                <p class="empty-tip">输入任何问题，AI助手将为您提供帮助</p>
              </template>
            </el-empty>
            <el-empty 
              :image-size="100" 
              description="开始聊天吧！"
              v-else
            />
          </div>
        </div>

        <!-- 文件上传组件 -->
        <el-dialog
          v-model="showFileUploader"
          title="上传文件"
          width="500px"
          center
        >
          <FileUploader @file-uploaded="handleFileUploaded" />
        </el-dialog>
        
        <!-- 消息输入区域 -->
        <div class="input-area">
          <el-form @submit.prevent="sendMessage">
            <el-input
              v-model="inputMessage"
              placeholder="请输入消息..."
              @keyup.enter="sendMessage"
              :disabled="loading"
              clearable
              type="textarea"
              :rows="2"
              resize="none"
              class="message-input"
            ></el-input>
            <div class="input-actions">
              <el-button 
                type="default" 
                @click="showFileUploader = true"
                :disabled="loading"
                class="upload-button"
              >
                <el-icon><Upload /></el-icon>
                上传文件
              </el-button>
              <el-button 
                type="primary" 
                @click="sendMessage" 
                :loading="loading"
                :disabled="!inputMessage.trim() || loading"
                class="send-button"
              >
                发送
                <el-icon class="send-icon"><Send /></el-icon>
              </el-button>
            </div>
          </el-form>
        </div>
      </section>

      <!-- 未选择聊天室提示 -->
      <section class="no-room-selected" v-else>
        <el-empty 
          :image-size="120" 
          description="请选择一个聊天室开始对话"
        />
      </section>
    </main>

    <!-- 创建聊天室对话框 -->
    <el-dialog
      v-model="showCreateRoomDialog"
      title="创建新聊天室"
      width="400px"
      center
    >
      <el-form :model="roomForm" :rules="roomRules" ref="roomFormRef" label-width="80px">
        <el-form-item label="聊天室名" prop="name">
          <el-input 
            v-model="roomForm.name" 
            placeholder="请输入聊天室名称" 
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="聊天室类型" prop="roomType">
          <el-radio-group v-model="roomForm.roomType">
            <el-radio value="private">
              <el-icon><User /></el-icon>
              私聊
            </el-radio>
            <el-radio value="group">
              <el-icon><ChatLineSquare /></el-icon>
              群聊
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="roomForm.roomType === 'group'" label="群成员ID" prop="memberIdsInput">
          <el-input 
            v-model="roomForm.memberIdsInput" 
            placeholder="请输入成员ID，用逗号分隔"
            type="textarea"
            :rows="2"
          />
          <div class="form-tip">提示：当前用户会自动添加为成员</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelCreateRoom">取消</el-button>
        <el-button type="primary" @click="handleCreateRoom" :loading="creatingRoom">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { authService } from '../services/authService';
import { chatRoomService } from '../services/chatRoomService';
import { aiService } from '../services/aiService';
import { 
  ChatDotRound, 
  User, 
  ChatLineSquare, 
  Setting, 
  ArrowDown, 
  Send, 
  Plus, 
  SwitchButton,
  Upload
} from '@element-plus/icons-vue'
import FileUploader from '../components/FileUploader.vue'

export default {
  name: 'ChatHome',
  components: {
    ChatDotRound,
    User,
    ChatLineSquare,
    Setting,
    ArrowDown,
    Send,
    Plus,
    SwitchButton,
    Upload,
    FileUploader
  },
  data() {
    return {
      inputMessage: '',
      loading: false,
      creatingRoom: false,
      showFileUploader: false,
      messages: [],
      chatRooms: [],
      currentUser: null,
      aiRoom: null,
      currentRoom: null,
      showCreateRoomDialog: false,
      isAdmin: false,
      roomForm: {
        name: '',
        roomType: 'private',
        memberIdsInput: ''
      },
      // 表单验证规则
      roomRules: {
        name: [
          { required: true, message: '请输入聊天室名称', trigger: 'blur' },
          { min: 2, max: 20, message: '聊天室名称长度应在2-20个字符之间', trigger: 'blur' }
        ],
        roomType: [
          { required: true, message: '请选择聊天室类型', trigger: 'change' }
        ],
        memberIdsInput: [
          { 
            validator: (rule, value, callback) => {
              if (this.roomForm.roomType === 'group' && !value.trim()) {
                callback(new Error('群聊必须指定成员'));
              } else if (value.trim()) {
                // 验证成员ID格式
                const ids = value.split(',').map(id => id.trim()).filter(id => id);
                for (const id of ids) {
                  if (!/^\d+$/.test(id)) {
                    callback(new Error('成员ID必须是数字'));
                    return;
                  }
                }
              }
              callback();
            }, 
            trigger: 'blur' 
          }
        ]
      },
      // AI模型相关数据
      aiModels: [],
      selectedModelId: 'qwen-turbo', // 默认选择通义千问Turbo模型
      currentModel: { id: 'qwen-turbo', name: '通义千问 Turbo', description: '高性能模型，响应迅速', type: 'free' },
      // 模型类型定义
      modelTypes: { free: '免费模型', premium: '高级模型' },
      // UI状态
      showModelDropdown: false
    }
  },
  computed: {
    // 获取分组后的模型列表
    groupedModels() {
      return aiService.groupModelsByType(this.aiModels);
    },
    // 获取有模型的类型列表
    availableModelTypes() {
      const modelsByType = this.getModelsByType()
      return Object.keys(this.modelTypes).filter(type => modelsByType[type].length > 0)
    }
  },
  mounted() {
    this.initializeApp();
    // 监听点击外部区域关闭下拉菜单等
    document.addEventListener('click', this.handleDocumentClick);
  },
  beforeUnmount() {
    document.removeEventListener('click', this.handleDocumentClick);
  },
  methods: {
    // 初始化应用
    async initializeApp() {
      try {
        await Promise.all([
          this.loadCurrentUser(),
          this.loadChatRooms(),
          this.loadAIModels()
        ]);
        // 默认选中AI聊天室
        if (this.aiRoom) {
          this.switchRoom(this.aiRoom);
          // 加载AI聊天室的欢迎消息
          this.loadAIMessages();
        }
      } catch (error) {
          console.error('初始化应用失败:', error);
          this.$message.error('初始化失败，请刷新页面重试');
        }
      },
    
    // 加载当前用户信息
    async loadCurrentUser() {
      try {
        this.currentUser = await authService.getCurrentUser();
        // 检查是否是管理员
        this.isAdmin = await authService.isAdmin();
        console.log('是否管理员:', this.isAdmin);
      } catch (error) {
        console.error('加载用户信息失败:', error);
        this.$message.error('加载用户信息失败');
        // 如果获取用户信息失败，可能是token过期，跳转到登录页
        authService.logout();
        this.$router.push('/login');
      }
    },
    
    // 加载聊天室列表
    async loadChatRooms() {
      try {
        // 创建默认的AI聊天室
        this.aiRoom = {
          id: 'ai-chat',
          name: 'AI 助手',
          roomType: 'ai'
        };
        
        // 从服务器加载用户的聊天室
        const rooms = await chatRoomService.getUserChatRooms();
        
        // 过滤掉AI聊天室（单独处理），只保留用户创建的聊天室
        this.chatRooms = rooms.filter(room => room.roomType !== 'ai') || [];
        console.log('成功加载聊天室列表，共', this.chatRooms.length, '个用户聊天室');
      } catch (error) {
        console.error('加载聊天室列表失败:', error);
        this.$message.error('加载聊天室列表失败');
        // 降级处理：使用空数组
        this.chatRooms = [];
      }
    },
    
    // 加载AI模型列表
    async loadAIModels() {
      try {
        const models = await aiService.getAvailableModels();
        this.aiModels = models || [];
        
        // 确保当前选中的模型存在，如果不存在则选择第一个
        if (!this.aiModels.find(model => model.id === this.selectedModelId) && this.aiModels.length > 0) {
          this.onModelChange(this.aiModels[0]);
        }
      } catch (error) {
        console.error('加载AI模型列表失败:', error);
        // 使用默认模型数据作为降级方案
          this.aiModels = [
            { id: 'qwen-turbo', name: '通义千问 Turbo', description: '高性能模型，响应迅速，适合日常对话', type: 'free' },
            { id: 'qwen-plus', name: '通义千问 Plus', description: '高级模型，能力更强，适合复杂任务', type: 'free' },
            { id: 'qwen-max', name: '通义千问 Max', description: '专业模型，性能最强，适合专业领域', type: 'free' }
          ];
      }
    },
    
    // 加载AI聊天室欢迎消息
    loadAIMessages() {
      this.messages = [
        {
          id: 1,
          content: '欢迎使用AI聊天助手！',
          senderType: 'ai',
          timestamp: new Date()
        },
        {
          id: 2,
          content: '可以点击右上角的「创建聊天室」按钮来创建新的聊天。',
          senderType: 'ai',
          timestamp: new Date(Date.now() + 1000)
        },
        {
          id: 3,
          content: '支持两种模式：1. 与AI助手聊天 2. 创建人人聊天室（私聊或群聊）',
          senderType: 'ai',
          timestamp: new Date(Date.now() + 2000)
        }
      ];
    },
    
    // 发送消息
    async sendMessage() {
      if (!this.inputMessage.trim()) {
        return
      }
      
      if (!this.currentRoom) {
        this.$message.error('请先选择聊天室')
        return
      }
      
      this.loading = true
      const messageContent = this.inputMessage.trim()
      this.inputMessage = '' // 清空输入框
      
      // 先将用户消息添加到消息列表
      const userMessage = {
        id: Date.now(),
        content: messageContent,
        senderType: 'user',
        senderName: this.currentUser?.username || '用户',
        timestamp: new Date()
      }
      this.messages.push(userMessage);
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
      
      try {
        if (this.currentRoom.roomType === 'ai') {
          // AI聊天 - 使用aiService发送消息给AI，传递选定的模型
          const aiResponse = await aiService.sendMessageToAI(messageContent, this.selectedModelId);
          const aiMessage = {
            id: Date.now() + 1,
            content: aiResponse.response || aiResponse.content || 'AI回复失败',
            senderType: 'ai',
            senderName: this.currentModel.name,
            timestamp: new Date()
          }
          this.messages.push(aiMessage);
        } else {
          // 普通聊天室消息 - 使用chatRoomService发送到后端
          await chatRoomService.sendMessage(this.currentRoom.id, messageContent)
          
          // 重新加载消息列表以获取最新消息
          await this.loadRoomMessages(this.currentRoom.id)
        }
      } catch (error) {
        console.error('发送消息失败:', error);
        // 不显示错误提示，因为我们已经有了模拟响应
        // 不再恢复输入框内容，因为用户消息已经显示在界面上
      } finally {
        this.loading = false;
        this.scrollToBottom();
      }
    },
    
    // 切换聊天室
    async switchRoom(room) {
      if (this.currentRoom?.id === room.id) {
        return;
      }
      
      this.currentRoom = room;
      this.messages = [];
      
      if (room.roomType !== 'ai') {
        // 加载聊天室历史消息
        try {
          const historyMessages = await chatRoomService.getChatRoomMessages(room.id);
          this.messages = historyMessages || [];
          
          // 如果没有历史消息，显示欢迎消息
          if (this.messages.length === 0) {
            this.messages = [
              {
                id: Date.now(),
                content: `欢迎进入聊天室！这是一个${room.roomType === 'private' ? '私聊' : '群聊'}房间。`,
                senderType: 'system',
                senderName: '系统',
                timestamp: new Date()
              }
            ];
          }
        } catch (error) {
          console.error('加载历史消息失败:', error);
          this.$message.error('加载历史消息失败');
          // 使用模拟数据
          this.messages = [
            {
              id: Date.now(),
              content: `欢迎进入聊天室！这是一个${room.roomType === 'private' ? '私聊' : '群聊'}房间。`,
              senderType: 'system',
              senderName: '系统',
              timestamp: new Date()
            }
          ];
        }
      } else {
        // 加载AI聊天室欢迎消息
        this.loadAIMessages();
      }
      
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    
    // 取消创建聊天室
    cancelCreateRoom() {
      this.showCreateRoomDialog = false;
      this.$nextTick(() => {
        if (this.$refs.roomForm) {
          this.$refs.roomForm.resetFields();
        }
        this.roomForm.roomType = 'private';
        this.roomForm.memberIdsInput = '';
      });
    },
    
    // 切换AI模型
    onModelChange(model) {
      this.selectedModelId = model.id;
      this.currentModel = model;
      this.$message.success(`已切换到 ${model.name}`);
    },
    
    // 删除聊天室
    async deleteRoom(roomId) {
      try {
        const confirm = await this.$confirm('确定要删除该聊天室吗？此操作不可撤销，所有聊天记录将被删除。', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        if (confirm) {
          this.loading = true
          // 调用API删除聊天室
          await chatRoomService.deleteRoom(roomId)
          
          // 从列表中移除聊天室
          this.chatRooms = this.chatRooms.filter(room => room.id !== roomId)
          
          // 如果当前在该聊天室，切换到其他聊天室或清空当前聊天室
          if (this.currentRoom && this.currentRoom.id === roomId) {
            if (this.chatRooms.length > 0) {
              await this.switchRoom(this.chatRooms[0])
            } else {
              this.currentRoom = null
              this.messages = []
            }
          }
          
          this.$message.success('聊天室删除成功')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除聊天室失败:', error)
          this.$message.error('删除聊天室失败，请重试')
        }
      } finally {
        this.loading = false
      }
    },
    
    // 滚动到底部
    scrollToBottom() {
      const messageContainer = this.$refs.messageList;
      if (messageContainer) {
        messageContainer.scrollTop = messageContainer.scrollHeight;
      }
    },
    
    // 格式化日期时间
    formatDate(timestamp) {
      const date = new Date(timestamp);
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },
    
    // 格式化消息内容，支持Markdown链接格式
    formatMessageContent(message) {
      if (message.fileMetadata) {
        // 对于文件消息，返回带有点击提示的内容
        return `${message.content} <span class="click-hint" title="点击预览或下载">[点击操作]</span>`
      }
      // 对于普通消息，返回原始内容（可以根据需要扩展为支持简单的Markdown格式）
      return message.content
    },
    
    // 处理文档点击，用于关闭下拉菜单等
    handleDocumentClick(event) {
      const modelSelector = event.target.closest('.model-selector');
      if (!modelSelector) {
        this.showModelDropdown = false;
      }
    },
    

    
    // 加载AI模型列表
    
    // 按类型获取模型
    getModelsByType(type) {
      if (type) {
        // 如果提供了类型参数，返回该类型的模型列表
        return this.aiModels.filter(model => model.type === type)
      } else {
        // 否则返回所有类型的模型分组
        const modelsByType = {}
        Object.keys(this.modelTypes).forEach(t => {
          modelsByType[t] = this.aiModels.filter(model => model.type === t)
        })
        return modelsByType
      }
    },
    
    // 获取当前模型名称
    getCurrentModelName() {
      return this.currentModel?.name || 'AI助手'
    },
    
    // 切换模型下拉菜单显示状态
    toggleModelDropdown() {
      this.showModelDropdown = !this.showModelDropdown
    },
    
    // 点击外部关闭模型下拉菜单
    handleClickOutside(event) {
      const modelSelector = document.querySelector('.ai-model-selector')
      if (modelSelector && !modelSelector.contains(event.target)) {
        this.showModelDropdown = false
      }
    },
    
    async loadMessages() {
      try {
        this.loading = true
        // 模拟AI聊天消息
        this.messages = [
          {
            id: 1,
            content: '欢迎使用AI聊天助手！',
            senderType: 'ai',
            timestamp: new Date()
          },
          {
            id: 2,
            content: '可以点击右上角的「创建聊天室」按钮来创建新的聊天。',
            senderType: 'ai',
            timestamp: new Date(Date.now() + 1000)
          },
          {
            id: 3,
            content: '支持两种模式：1. 与AI助手聊天 2. 创建人人聊天室（私聊或群聊）',
            senderType: 'ai',
            timestamp: new Date(Date.now() + 2000)
          }
        ]
      } catch (error) {
        console.error('Load messages error:', error)
      } finally {
        this.loading = false
      }
    },
    
    async loadRoomMessages(roomId) {
      try {
        this.loading = true
        // 调用后端API获取真实的聊天记录
        const messages = await chatRoomService.getChatRoomMessages(roomId)
        this.messages = messages || []
        console.log('成功加载聊天室消息，共', this.messages.length, '条消息')
      } catch (error) {
        console.error('加载聊天室消息失败:', error)
        this.messages = []
        this.$message.error('加载聊天记录失败')
      } finally {
        this.loading = false
      }
    },
    async loadUserChatRooms() {
      try {
        // 调用后端API获取真实的聊天室列表
        const rooms = await chatRoomService.getUserChatRooms()
        
        // 过滤掉AI聊天室（单独处理），只保留用户创建的聊天室
        this.chatRooms = rooms.filter(room => room.roomType !== 'ai')
        console.log('成功加载用户聊天室列表，共', this.chatRooms.length, '个聊天室')
      } catch (error) {
        console.error('加载用户聊天室列表失败:', error)
        this.$message.error('加载聊天室列表失败')
      }
    },
    async handleCreateRoom() {
      if (!this.roomForm.name.trim()) {
        this.$message.error('请输入聊天室名称')
        return
      }
      
      this.creatingRoom = true
      
      try {
        // 准备聊天室数据
        const roomData = {
          name: this.roomForm.name.trim(),
          roomType: this.roomForm.roomType
        }
        
        // 调用后端API创建聊天室
        const newRoom = await chatRoomService.createChatRoom(roomData)
        
        // 添加到聊天室列表
        this.chatRooms.push(newRoom)
        
        // 切换到新创建的聊天室
        await this.switchRoom(newRoom)
        
        this.$message.success('聊天室创建成功')
        this.showCreateRoomDialog = false
        
        // 重置表单
        this.roomForm = {
          name: '',
          roomType: 'private',
          memberIdsInput: ''
        }
      } catch (error) {
        console.error('Create room error:', error)
        this.$message.error('聊天室创建失败，请重试')
      } finally {
        this.creatingRoom = false
      }
    },

    async handleLogout() {
      try {
        // 显示确认对话框
        const confirmResult = await this.$confirm('确定要退出登录吗？', '退出登录', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => false)
        
        // 如果用户确认退出
        if (confirmResult) {
          // 显示加载状态
          this.$loading({
            lock: true,
            text: '正在退出...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          
          // 调用退出登录服务
          await authService.logout()
          
          // 显示成功消息
          this.$message.success('退出登录成功')
          
          // 跳转到登录页面
          this.$router.push('/login')
        }
      } catch (error) {
        console.error('退出登录失败:', error)
        this.$message.error('退出登录失败，请重试')
      } finally {
        // 关闭加载状态
        this.$loading().close()
      }
    },
    
    // 处理文件上传成功
    handleFileUploaded(fileInfo) {
      try {
        console.log('文件上传成功:', fileInfo)
        this.showFileUploader = false
        
        // 构建完整的文件URL，确保可以正确访问
        let fileUrl = fileInfo.fileUrl || ''
        
        // 智能构建完整URL，适配不同的后端API路径格式
        if (!(fileUrl.startsWith('http://') || fileUrl.startsWith('https://'))) {
          const baseUrl = window.location.origin
          
          if (fileUrl.startsWith('/')) {
            // 已经是绝对路径，直接添加域名
            fileUrl = `${baseUrl}${fileUrl}`
          } else if (fileUrl.startsWith('api/')) {
            // 已经包含api前缀
            fileUrl = `${baseUrl}/${fileUrl}`
          } else {
            // 处理文件名或简单路径的情况
            // 尝试两种常见的后端文件访问模式
            // 1. 直接通过文件名访问（如果后端支持）
            // 2. 通过标准的文件访问API路径
            // 优先使用/api/file/路径，这是更常见的后端API设计
            fileUrl = `${baseUrl}/api/file/${fileUrl}`
          }
        }
        
        // 根据文件类型添加适当的图标
        let fileIcon = '📄'
        const ext = fileInfo.filename.split('.').pop().toLowerCase()
        if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(ext)) {
          fileIcon = '🖼️'
        } else if (['pdf'].includes(ext)) {
          fileIcon = '📑'
        } else if (['doc', 'docx'].includes(ext)) {
          fileIcon = '📝'
        } else if (['xls', 'xlsx', 'csv'].includes(ext)) {
          fileIcon = '📊'
        } else if (['mp4', 'avi', 'mov', 'wmv', 'flv'].includes(ext)) {
          fileIcon = '🎬'
        } else if (['mp3', 'wav', 'ogg', 'flac'].includes(ext)) {
          fileIcon = '🎵'
        } else if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) {
          fileIcon = '📦'
        } else if (['txt', 'md', 'log'].includes(ext)) {
          fileIcon = '📃'
        } else if (['js', 'html', 'css', 'vue', 'json', 'ts', 'py', 'java', 'cpp'].includes(ext)) {
          fileIcon = '💻'
        }
        
        // 创建文件消息对象
        const fileMessage = {
          id: Date.now(),
          content: `${fileIcon} [${fileInfo.filename}](${fileUrl})`,
          senderType: 'user',
          senderName: this.currentUser?.username || '用户',
          timestamp: new Date(),
          // 添加文件元数据，用于处理预览和下载
          fileMetadata: {
            filename: fileInfo.filename,
            url: fileUrl,
            extension: ext,
            size: fileInfo.size || 0
          }
        }
        
        // 将文件消息直接添加到消息列表，而不是输入框
        this.messages.push(fileMessage)
        
        // 显示成功提示
        this.$message.success(`文件上传成功：${fileInfo.filename}`)
        
        // 自动滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })
        
        // 如果是AI聊天室，尝试获取AI对文件的处理结果
        if (this.currentRoom?.roomType === 'ai') {
          this.handleAIFileAnalysis(fileInfo.filename, fileUrl, ext)
        }
      } catch (error) {
        console.error('处理文件上传结果失败:', error)
        this.$message.error('文件上传成功，但处理文件信息时出错')
      }
    },
    
    // 处理文件点击（预览或下载）
    handleFileClick(message) {
      try {
        if (!message.fileMetadata) return
        
        const { url, filename, extension } = message.fileMetadata
        console.log('文件点击:', url, filename, extension)
        
        // 对于常见的可预览文件类型，在新标签页中打开
        if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(extension)) {
          // 图片直接预览
          window.open(url, '_blank')
        } else if (['pdf'].includes(extension)) {
          // PDF在新标签页中预览
          window.open(url, '_blank')
        } else if (['mp4', 'avi', 'mov', 'wmv', 'flv'].includes(extension)) {
          // 视频在新标签页中播放
          window.open(url, '_blank')
        } else if (['mp3', 'wav', 'ogg', 'flac'].includes(extension)) {
          // 音频在新标签页中播放
          window.open(url, '_blank')
        } else if (['txt', 'md', 'log', 'js', 'html', 'css', 'json'].includes(extension)) {
          // 文本文件在新标签页中打开
          window.open(url, '_blank')
        } else {
          // 其他类型直接下载
          this.downloadFile(url, filename)
        }
      } catch (error) {
        console.error('处理文件点击时出错:', error)
        this.$message.error('操作文件时出错')
      }
    },
    
    // 下载文件
    downloadFile(url, filename) {
      try {
        // 创建下载链接
        const link = document.createElement('a')
        link.href = url
        link.download = filename || 'download'
        link.style.display = 'none'
        
        // 添加到DOM并触发点击
        document.body.appendChild(link)
        link.click()
        
        // 清理
        setTimeout(() => {
          document.body.removeChild(link)
        }, 100)
        
        this.$message.success(`开始下载文件: ${filename}`)
      } catch (error) {
        console.error('下载文件失败:', error)
        this.$message.error('文件下载失败，请稍后重试')
      }
    },
    
    // 处理AI对文件的分析（模拟）
    async handleAIFileAnalysis(filename, fileUrl, extension) {
      try {
        this.loading = true
        
        // 模拟AI处理文件的延迟
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 根据文件类型生成不同的AI回复
        let aiResponse = ''
        if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'].includes(extension)) {
          aiResponse = `我看到你上传了一张图片：${filename}。如果你需要我分析图片内容，请告诉我你想了解什么。`
        } else if (['pdf'].includes(extension)) {
          aiResponse = `你上传了PDF文件：${filename}。我可以帮你总结文件内容、提取关键信息或回答关于文件的问题。`
        } else if (['doc', 'docx', 'txt', 'md'].includes(extension)) {
          aiResponse = `我收到了你上传的文档：${filename}。请告诉我你希望我如何帮助处理这份文档。`
        } else if (['xls', 'xlsx', 'csv'].includes(extension)) {
          aiResponse = `你上传了表格文件：${filename}。我可以帮你分析数据、提取统计信息或生成报告。`
        } else {
          aiResponse = `我收到了你上传的文件：${filename}。请问你希望我如何处理这个文件？`
        }
        
        // 添加AI回复到消息列表
        const aiMessage = {
          id: Date.now() + 1,
          content: aiResponse,
          senderType: 'ai',
          senderName: this.currentModel?.name || 'AI助手',
          timestamp: new Date()
        }
        this.messages.push(aiMessage)
        
        // 自动滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      } catch (error) {
        console.error('AI文件分析失败:', error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.home-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  overflow: hidden;
}

/* 顶部导航栏样式 */
.navbar {
  height: 60px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  z-index: 100;
}

.navbar-logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: bold;
  color: #1890ff;
  cursor: pointer;
}

.navbar-user {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.user-avatar:hover {
  border-color: #1890ff;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧聊天室列表样式 */
.sidebar {
  width: 320px;
  background-color: #ffffff;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.room-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.room-item {
  padding: 12px 16px;
  margin-bottom: 4px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.room-item:hover {
  background-color: #f5f5f5;
}

.room-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
}

.room-info {
  flex: 1;
  min-width: 0;
}

.room-name {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.room-meta {
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 右侧聊天区域样式 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  position: relative;
}

.chat-header {
  padding: 16px 24px;
  background-color: #ffffff;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.chat-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* AI模型选择器样式 */
.model-selector {
  margin-right: 16px;
}

.model-selector .el-dropdown {
  position: relative;
}

.model-dropdown-trigger {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 6px;
  background-color: #f0f2f5;
  transition: all 0.3s;
  cursor: pointer;
}

.model-dropdown-trigger:hover {
  background-color: #e6f7ff;
}

.model-dropdown-content {
  min-width: 240px;
  padding: 8px 0;
}

.model-type-group {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.model-type-title {
  padding: 0 16px;
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
  font-weight: 500;
}

.model-option {
  padding: 10px 16px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  transition: all 0.2s;
}

.model-option:hover {
  background-color: #f5f7fa;
}

.model-option.active {
  background-color: #e6f7ff;
  color: #1890ff;
}

.model-name {
  font-weight: 500;
  margin-bottom: 2px;
}

.model-desc {
  font-size: 12px;
  color: #666;
}

/* 消息列表样式 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background-color: #f5f7fa;
  background-image: 
    radial-gradient(rgba(24, 144, 255, 0.05) 2px, transparent 0),
    radial-gradient(rgba(24, 144, 255, 0.05) 2px, transparent 0);
  background-size: 30px 30px;
  background-position: 0 0, 15px 15px;
}

.message-wrapper {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
}

.message-wrapper.user {
  align-items: flex-end;
}

.message-wrapper.ai,
.message-wrapper.system {
  align-items: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 12px;
  word-wrap: break-word;
  position: relative;
}

.message-wrapper.user .message-content {
  background-color: #1890ff;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-wrapper.ai .message-content {
  background-color: #ffffff;
  color: #333;
  border-bottom-left-radius: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.message-wrapper.error .message-content {
  background-color: #fff2f0;
  color: #f5222d;
  border: 1px solid #ffccc7;
  border-bottom-left-radius: 4px;
}

.message-header {
  font-size: 12px;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.message-wrapper.user .message-header {
  color: #999;
}

.message-wrapper.ai .message-header {
  color: #666;
}

.message-time {
  font-size: 11px;
  color: #999;
}

/* 输入框样式 */
.input-area {
  padding: 16px 24px;
  background-color: #ffffff;
  border-top: 1px solid #e8e8e8;
  display: flex;
  align-items: flex-end;
  gap: 12px;
}

.message-input {
  flex: 1;
  min-height: 40px;
  max-height: 120px;
  resize: none;
  border-radius: 8px;
  border: 1px solid #d9d9d9;
  padding: 10px 12px;
  font-size: 14px;
  line-height: 1.5;
  transition: border-color 0.3s;
}

.message-input:focus {
  outline: none;
  border-color: #1890ff;
}

.send-button {
  min-width: 40px;
  height: 40px;
  border-radius: 8px;
}

/* 按钮样式 */
.primary-button {
  background-color: #1890ff;
  color: white;
  border: none;
  transition: all 0.3s;
}

.primary-button:hover:not(:disabled) {
  background-color: #40a9ff;
}

.primary-button:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.secondary-button {
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #d9d9d9;
  transition: all 0.3s;
}

.secondary-button:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

/* 创建聊天室对话框样式 */
.create-room-dialog .el-dialog__header {
  padding: 20px 24px 16px;
}

.create-room-dialog .el-dialog__body {
  padding: 20px 24px;
}

.create-room-dialog .form-item {
  margin-bottom: 20px;
}

/* 空状态样式 */
.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  padding: 40px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  margin-bottom: 8px;
}

.empty-description {
  font-size: 14px;
  text-align: center;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-wrapper {
  animation: fadeIn 0.3s ease;
}

/* 滚动条样式 */
.room-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.room-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.room-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.room-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 100%;
    position: absolute;
    left: -100%;
    transition: left 0.3s ease;
    z-index: 101;
  }
  
  .sidebar.show {
    left: 0;
  }
  
  .message-content {
    max-width: 85%;
  }
}

.chat-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-info span {
  font-size: 16px;
  font-weight: 500;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 300px;
  background-color: white;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  box-shadow: 2px 0 4px rgba(0, 0, 0, 0.05);
}

.sidebar-header {
  padding: 20px 15px;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fafafa;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.room-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.room-item {
  padding: 14px 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-bottom: 1px solid #f5f5f5;
}

.room-item:hover {
  background-color: #f7f7f7;
  transform: translateX(2px);
}

.room-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-right: 4px solid #1890ff;
  font-weight: 500;
}

.room-item .el-icon {
  font-size: 20px;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fafafa;
}

.room-header {
      padding: 15px 20px;
      background-color: white;
      border-bottom: 1px solid #e8e8e8;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    }

    .room-title-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
    }

    .room-header h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
    
    .room-title-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
    }

    /* AI模型选择器样式 */
    .ai-model-selector {
      position: relative;
    }
    
    .model-button {
      display: flex;
      align-items: center;
      gap: 5px;
      color: #409eff;
      padding: 4px 8px;
      border-radius: 4px;
      transition: background-color 0.3s;
      cursor: pointer;
    }
    
    .model-button:hover {
      background-color: #f0f9ff;
    }
    
    .model-dropdown {
      position: absolute;
      top: 100%;
      right: 0;
      margin-top: 4px;
      width: 280px;
      background-color: #fff;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      z-index: 1000;
      max-height: 300px;
      overflow-y: auto;
    }
    
    .model-type-header {
      padding: 8px 12px;
      background-color: #f5f7fa;
      color: #606266;
      font-size: 12px;
      font-weight: 500;
      border-bottom: 1px solid #ebeef5;
    }
    
    .model-item {
      padding: 12px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    
    .model-item:last-child {
      border-bottom: none;
    }
    
    .model-item:hover {
      background-color: #f5f5f5;
    }
    
    .model-item.active {
      background-color: #ecf5ff;
      border-left: 3px solid #409eff;
    }
    
    .model-name {
      font-weight: 500;
      font-size: 14px;
      margin-bottom: 4px;
    }
    
    .model-description {
      font-size: 12px;
      color: #606266;
      margin-bottom: 4px;
      line-height: 1.4;
    }
    
    .model-type {
      font-size: 11px;
      color: #909399;
      background-color: #f0f2f5;
      padding: 2px 6px;
      border-radius: 10px;
      display: inline-block;
    }

.room-header span {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background-color: #f5f5f5;
  background-image: 
    linear-gradient(rgba(0, 0, 0, 0.03) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 0, 0, 0.03) 1px, transparent 1px);
  background-size: 20px 20px;
}

.message-item {
  max-width: 75%;
  padding: 12px 16px;
  border-radius: 12px;
  word-wrap: break-word;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;
}

.message-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
}

.user-message {
  align-self: flex-end;
  background-color: #95ec69;
  border-bottom-right-radius: 4px;
}

.ai-message {
  align-self: flex-start;
  background-color: white;
  border-bottom-left-radius: 4px;
}

.message-sender {
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 6px;
  color: #555;
}

.message-content {
  font-size: 15px;
  line-height: 1.5;
  margin-bottom: 6px;
}

.message-time {
  font-size: 12px;
  color: #999;
  text-align: right;
}

.empty-messages {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
  font-size: 16px;
  text-align: center;
}

.chat-input {
  padding: 20px;
  background-color: white;
  border-top: 1px solid #e8e8e8;
  display: flex;
  gap: 10px;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.05);
}

.chat-input .el-input {
  flex: 1;
  border-radius: 20px;
  overflow: hidden;
}

.chat-input .el-button {
  border-radius: 20px;
  padding: 0 24px;
  font-weight: 500;
}

.upload-button {
  margin-right: 10px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

.upload-button:hover {
  background-color: #f0f9ff;
  border-color: #91d5ff;
}

.input-actions {
  display: flex;
  gap: 10px;
}

/* 创建聊天室对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background-color: #1890ff;
  color: white;
  padding: 15px 20px;
}

:deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

/* 滚动条样式美化 */
.room-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.room-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.room-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.room-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 250px;
  }
  
  .message-item {
    max-width: 85%;
  }
  
  .chat-input {
    padding: 15px;
  }
}
</style>